/*****************************************************************************************************
 *  @description 执行一段Node程序代码（Jenkins的Node脚本备份）
 *  1. 判断打包的是哪个项目文件
 *  2. 将打包后的文件进行压缩包处理
 *  3. 将打包文件移动到服务器部署对应的文件路径
 *  4. 将压缩包文件移动到chinadci文件夹的version, 进行版本管理
 *****************************************************************************************************/
const fs = require("fs");

const path = require("path");

const exec = require("child_process").execSync;

// WinRAR运行地址 路径有空格，需加上双引号
const winrar = `"C:\\Program Files\\WinRAR\\WinRAR.exe"`;

// 工作区
const workSpace = "D:\\webapp\\SvnWorkSpace\\wwsq_web";

// 部署区
const serverSpace = "D:\\webapp\\html";

// 项目名称
const projectName = require(`${workSpace}/config/project`).name;

// 由于项目在projects的命名与服务器部署为文件夹命名不一致, 需在此进行转换, 以此获得服务器的文件夹名称
const serverFolderName = require(`${workSpace}/config/serverFolderName`)(
    projectName
);

// 由于前端脚本出于安全问题, 需进行编码处理, 故要知道所构建项目调用的是哪个前端脚本和所需要替换的内容
const serverJavascript = require(`${workSpace}/config/serverJavascript`)(
    projectName
);

// 压缩包名称
const zipPackName = (function () {
    let t = new Date();
    let y = t.getFullYear();
    let m = t.getMonth() + 1;
    let d = t.getDate();
    let hh = t.getHours();
    let mm = t.getMinutes();
    let ss = t.getSeconds();

    m = m >= 10 ? m : `0${m}`;
    d = d >= 10 ? d : `0${d}`;
    hh = hh >= 10 ? hh : `0${hh}`;
    ss = ss >= 10 ? ss : `0${ss}`;

    return `${projectName}-${y}${m}${d}-${hh}${mm}${ss}`;
})();

// 被压缩的文件/文件夹内容汇总列表
const zipFiles = fs
    .readdirSync(`${workSpace}/dist/${projectName}`)
    .map((name) => {
        // 不能以.开头的文件/文件夹
        if (name[0] !== ".") {
            return `${workSpace}/dist/${projectName}/${name}`;
        }
    })
    .join(" ");

// 文件夹删除
const deleteFolder = function (path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                deleteFolder(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

// 检查文件夹是否存在
const onCheckedFolder = function (floderPath, floderName) {
    try {
        fs.statSync(path.resolve(floderPath, floderName));
        return true;
    } catch (err) {
        return false;
    }
};

const log = {
    success: function (content) {
        console.log(
            "\033[42;30m DCI SUCCESS \033[47;30m " + content + "\033[0m"
        );
    },
    fail: function (content) {
        console.log("\033[41;37m DCI FAIL \033[47;30m " + content + "\033[0m");
        throw new Error();
    },
};

// 删除.svn文件夹
deleteFolder(`${workSpace}/dist/${projectName}/.svn`);

// 2. 构建成功后的文件复制至公司服务器的部署路径
(function () {
    const from = `${workSpace}\\dist\\${projectName}`;
    const to = `${serverSpace}\\${serverFolderName}`;
    try {
        exec(`xcopy /y /c /h /r /s /q ${from} ${to}`, { stdio: "inherit" });
        log.success(`更新成功！项目为：${projectName}`);
    } catch (error) {
        log.fail(`更新服务器文件时发生错误。错误信息为：${error.message}`);
    }
})();

// 3. 修改构建成功后的文件（构建一份发布版本）
(function () {
    if (!serverJavascript) return;

    try {
        let replaceContent = serverJavascript.replace;
        let indexHtml = fs.readFileSync(
            `${workSpace}/dist/${projectName}/index.html`,
            "utf-8"
        );

        if (replaceContent && replaceContent.length > 0) {
            replaceContent.forEach((item, index) => {
                indexHtml = indexHtml.replace(
                    new RegExp(item.from, "gm"),
                    item.to
                );
            });
        }

        fs.writeFileSync(
            `${workSpace}/dist/${projectName}/index.html`,
            indexHtml,
            "utf8"
        );

        log.success(`构建发布版本成功`);
    } catch (error) {
        log.fail(`构建发布版本失败。错误信息为：${error}`);
    }
})();

// chinadci/version下是否存在对应文件夹
const isVersionFloder = onCheckedFolder(
    `${serverSpace}/chinadci/version/`,
    serverFolderName
);

log.success(`是否存在相应的版本管理文件夹：${isVersionFloder}`);

// 4. 压缩发布版本
(function () {
    if (!isVersionFloder) return;

    const from = `${workSpace}/dist/${projectName}/${zipPackName}`;
    const to = `${zipFiles}`;

    try {
        exec(`${winrar} a -r -ep1 ${from} ${to}`, { stdio: "inherit" });
        log.success(`已成功生成发布版压缩包：${zipPackName}.rar`);
    } catch (error) {
        log.fail(`发布版压缩包生成失败。错误信息为：${error}`);
    }
})();

// 5. 备份发布版压缩包（将压缩包文件移动到chinadci文件夹的version）
(function () {
    if (!isVersionFloder) return;

    const from = `${workSpace}\\dist\\${projectName}\\${zipPackName}.rar`;
    const to = `${serverSpace}\\chinadci\\version\\${serverFolderName}\\${zipPackName}.rar`;
    try {
        exec(`move /Y ${from} ${to}`, { stdio: "inherit" });
        log.success(
            `压缩包 ${zipPackName} 已移至 /chinadci/version/${serverFolderName}`
        );
        log.success(
            `压缩包下载地址为：http://39.108.58.158:8089/chinadci/version/${serverFolderName}/${zipPackName}.rar`
        );
    } catch (error) {
        log.fail(`备份发布版压缩包失败。错误信息为：${error.message}`);
    }
})();
